package com.zz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zz.common.R;
import com.zz.dto.ApplicationAuditingDto;
import com.zz.entity.*;
import com.zz.mapper.*;
import com.zz.service.ApplicationAuditingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ApplicationAuditingServiceImpl extends ServiceImpl<ApplicationAuditingMapper, ApplicationAuditing> implements ApplicationAuditingService {

    @Autowired
    private ApplicationAuditingMapper applicationAuditingMapper;

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SystemNoticeMapper systemNoticeMapper;

    @Autowired
    private AttendedMapper attendedMapper;

    /**
     * 同意活动报名的申请（leader）
     * @param applicationAuditing
     * @return
     */
    @Override
    public R<String> agreeApply(ApplicationAuditing applicationAuditing) {
        // 查询数据库中报名信息
        LambdaQueryWrapper<ApplicationAuditing> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApplicationAuditing::getUserId, applicationAuditing.getUserId());
        wrapper.eq(ApplicationAuditing::getActivityId, applicationAuditing.getActivityId());
        ApplicationAuditing one = applicationAuditingMapper.selectOne(wrapper);

        // 将操作字段改为1，表示同意报名
        one.setOperate(1);

        // 表示已经审核ol
        one.setStatus(1);

        // 修改数据库
        applicationAuditingMapper.updateById(one);

        // Activity表 已参加人数+1
        LambdaQueryWrapper<Activity> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Activity::getId, one.getActivityId());

        Activity one1 = activityMapper.selectOne(wrapper1);
        one1.setAttendedNumber(one1.getAttendedNumber()+1);

        activityMapper.updateById(one1);

        // 设置系统通知信息
        Activity activity = activityMapper.selectById(applicationAuditing.getActivityId());
        User user = userMapper.selectById(applicationAuditing.getUserId());
        SystemNotice systemNotice = new SystemNotice();
        systemNotice.setUserId(applicationAuditing.getUserId());
        systemNotice.setTitle("您收到一条来自社团的活动通知！");
        systemNotice.setInfo(user.getName()+"同学你好！恭喜你成功报名活动： "+ activity.getName()+"！请按时参加活动！活动时间："+activity.getTime());
        systemNotice.setTime(new Date(System.currentTimeMillis()));

        systemNoticeMapper.insert(systemNotice);

        // 已参加活动表添加数据
        Attended attended = new Attended();
        attended.setUserId(user.getId());
        attended.setActivityId(activity.getId());
        attendedMapper.insert(attended);

        return R.success("同意报名活动申请！");
    }

    /**
     * 不同意活动报名的申请（leader）
     * @param applicationAuditing
     * @return
     */
    @Override
    public R<String> notAgreeApply(ApplicationAuditing applicationAuditing) {
        // 查询数据库中报名信息
        LambdaQueryWrapper<ApplicationAuditing> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApplicationAuditing::getUserId, applicationAuditing.getUserId());
        wrapper.eq(ApplicationAuditing::getActivityId, applicationAuditing.getActivityId());
        ApplicationAuditing one = applicationAuditingMapper.selectOne(wrapper);

        // 将操作字段改为1，表示不同意报名
        one.setOperate(0);

        // 表示已经审核
        one.setStatus(1);

        // 修改数据库
        applicationAuditingMapper.updateById(one);

        // 设置系统通知信息
        Activity activity = activityMapper.selectById(applicationAuditing.getActivityId());
        User user = userMapper.selectById(applicationAuditing.getUserId());
        SystemNotice systemNotice = new SystemNotice();
        systemNotice.setUserId(applicationAuditing.getUserId());
        systemNotice.setTitle("您收到一条来自社团的活动通知！");
        systemNotice.setInfo(user.getName()+"同学你好！很遗憾！你未能成功报名参加活动： "+ activity.getName()+"！欢迎下次再见！");
        systemNotice.setTime(new Date(System.currentTimeMillis()));

        systemNoticeMapper.insert(systemNotice);

        return R.error("拒绝报名活动申请！");
    }

    /**
     * 分页展示报名申请列表(leader)
     * 朱彦燕
     * @param page
     * @param pageSize
     * 测试成功
     * */
    @Override
    public R<Page> applyList(int page, int pageSize, HttpServletRequest request) {
        // 构造分页构造器
        Page<ApplicationAuditing> pageInfo = new Page<>(page, pageSize);
        Page<ApplicationAuditingDto> applicationAuditingDtoPage = new Page<>(page, pageSize);

        // 从session中获取社团id
        int clubId = (int) request.getSession().getAttribute("club");
        log.info("当前社团id：{}",clubId);
        if (clubId == 0){
            return R.error("您还未选择社团进行管理！");
        }

        // 条件查询器，只选择属于本社团的活动
        LambdaQueryWrapper<Activity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Activity::getClubId, clubId);

        List<Activity> list = activityMapper.selectList(wrapper);

        // 将所有活动id 放入activityIds 集合中
        List<Integer> activityIds = new ArrayList<>();
        for (Activity activity : list) {
            activityIds.add(activity.getId());
        }

        // 条件过滤器
        LambdaQueryWrapper<ApplicationAuditing> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.in(ApplicationAuditing::getActivityId, activityIds);
        wrapper1.eq(ApplicationAuditing::getStatus, 0);

        // 执行分页查询
        // 在page方法内部会将查好的数据封装，赋好值给pageInfo
        applicationAuditingMapper.selectPage(pageInfo, wrapper1);

        log.info("pageInfo:{}",pageInfo.getRecords().toString());

        // 对象拷贝(除了records,records其实就是页面中一整行一整行数据)
        BeanUtils.copyProperties(pageInfo,applicationAuditingDtoPage,"records");

        List<ApplicationAuditing> records = pageInfo.getRecords();
        // 遍历list集合对象,item即为获取到的一个个ApplicationAuditing对象
        List<ApplicationAuditingDto> list1 = records.stream().map((item) -> {
            ApplicationAuditingDto applicationAuditingDto = new ApplicationAuditingDto();

            // 将其ApplicationAuditing中的数据复制给ApplicationAuditingDto
            BeanUtils.copyProperties(item, applicationAuditingDto);

            int userId = applicationAuditingDto.getUserId();
            int activityId = applicationAuditingDto.getActivityId();

            // 根据id查询分类对象
            User user = userMapper.selectById(userId);
            Activity activity = activityMapper.selectById(activityId);

            if(user != null){
                applicationAuditingDto.setUserName(user.getName());
            }

            applicationAuditingDto.setActivityName(activity.getName());
            applicationAuditingDto.setNumber(activity.getNumber());
            applicationAuditingDto.setAttendedNumber(activity.getAttendedNumber());

            return applicationAuditingDto;
        }).collect(Collectors.toList());

        applicationAuditingDtoPage.setRecords(list1);

        return R.success(applicationAuditingDtoPage);
    }
}
